#!/bin/bash

ERR_TO_NULL="2> /dev/null"
ALL_TO_NULL="$ERR_TO_NULL 1> /dev/null"

if [[ $# -ne 1 ]]; then
    echo "Archive doesn't specified!"
    exit 1
fi

if [[ $(eval $ERR_TO_NULL which "feh") == "" ]]; then
    echo "'feh' doesn't installed!"
    exit 1
fi

if [[ $(eval $ERR_TO_NULL which "unzip") == ""  ]]; then
    echo "'unzip' doesn't installed!"
    exit 1
fi

if [[ -d "$1" ]]; then
    echo "Directory doesn't allowed!"
    exit 1
fi

ARCHIVE=$(printf "%q" "$1")
SPACE_AVAILABLE=$(df -B1 $HOME | tail -1 | awk '{print $4}')
ARCHIVE_SIZE=$(ls -l "$1" | awk '{print $5}')

if [[ $(("$SPACE_AVAILABLE <= $ARCHIVE_SIZE" | bc)) -eq 1 ]]; then
    echo "Not enough space to restore archive!"
    exit 1
fi

CACHE="$HOME/.image_cache_$RANDOM" 

function cleanup {
    echo "Cleaning up..."
    eval $ALL_TO_NULL rm -rf $CACHE
		
    while [[ $? -ne 0  ]]
    do
	eval $ALL_TO_NULL rm -rf $CACHE
    done
    echo "Cleaned up! Bye!"
}

mkdir $CACHE 
echo "Reading files..."

eval $ALL_TO_NULL unzip -qq $ARCHIVE -d $CACHE &

UNZIP_PID=$!

if [[ $? -ne 0 ]]; then
    echo "Unable to read files!"
    cleanup
    exit 1
else
    echo "Files readed! Showing..."
fi

eval $ALL_TO_NULL feh --reload 0.1 --fullscreen --scale-down --borderless $CACHE
eval $ALL_TO_NULL kill -15 $UNZIP_PID

cleanup
